"""
订单记录管理器
"""
from typing import List, Dict, Any, Optional
from datetime import datetime
from sqlalchemy import desc
from .models import OrderRecord
from .sqlalchemy_database import SQLAlchemyDatabaseManager

class OrderRecordManager:
    def __init__(self):
        """
        初始化订单记录管理器
        """
        self.db = SQLAlchemyDatabaseManager()

    def get_record_by_id(self, record_id: int) -> Optional[Dict[str, Any]]:
        """
        根据ID获取订单记录
        :param record_id: 记录ID
        :return: 记录信息字典或None
        """
        record = self.db.get_by_id(OrderRecord, record_id)
        return self._convert_model_to_dict(record) if record else None

    def get_record_by_order_no(self, order_no: str) -> Optional[Dict[str, Any]]:
        """
        根据订单号获取记录
        :param order_no: 订单号
        :return: 记录信息
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            record = query.filter(OrderRecord.order_no == order_no).first()
            return self._convert_model_to_dict(record) if record else None
        finally:
            session.close()

    def get_records_by_account_id(self, account_id: int) -> List[Dict[str, Any]]:
        """
        获取指定账号的所有订单记录
        :param account_id: 账号ID
        :return: 记录列表
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            records = query.filter(OrderRecord.account_id == account_id).all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def get_records_by_task_id(self, task_id: int) -> List[Dict[str, Any]]:
        """
        获取指定任务的所有订单记录
        :param task_id: 任务ID
        :return: 记录列表
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            records = query.filter(OrderRecord.task_id == task_id).all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def get_records_by_status(self, buy_status: int = None, offer_status: int = None) -> List[Dict[str, Any]]:
        """
        根据状态获取订单记录
        :param buy_status: 购买状态
        :param offer_status: 报价状态
        :return: 记录列表
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            if buy_status is not None:
                query = query.filter(OrderRecord.buy_status == buy_status)
            if offer_status is not None:
                query = query.filter(OrderRecord.offer_status == offer_status)
                
            records = query.all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def get_recent_records(self, limit: int = 100, offset: int = 0) -> List[Dict[str, Any]]:
        """
        获取最近的订单记录
        :param limit: 限制数量
        :param offset: 偏移量
        :return: 记录列表
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            records = query.order_by(desc(OrderRecord.create_at))\
                .limit(limit)\
                .offset(offset)\
                .all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def search_records(self, keyword: str = None, limit: int = None, offset: int = None) -> List[Dict[str, Any]]:
        """
        搜索订单记录
        :param keyword: 搜索关键词
        :param limit: 限制数量
        :param offset: 偏移量
        :return: 记录列表
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            if keyword:
                query = query.filter(OrderRecord.task_name.like(f"%{keyword}%"))  # 只按任务名称搜索
            
            # 先排序
            query = query.order_by(desc(OrderRecord.create_at))
            
            # 再分页
            if limit is not None and offset is not None:
                query = query.limit(limit).offset(offset)
                
            records = query.all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def get_record_count(self, keyword: str = None) -> int:
        """
        获取记录总数
        :param keyword: 搜索关键词
        :return: 记录总数
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            if keyword:
                query = query.filter(OrderRecord.task_name.like(f"%{keyword}%"))  # 只按任务名称搜索
            return query.count()
        finally:
            session.close()

    def add_record(self, record_data: Dict[str, Any]) -> int:
        """
        添加新订单记录
        :param record_data: 记录数据
        :return: 新记录的ID
        """
        record_data = self._prepare_record_data(record_data)
        record = OrderRecord(**record_data)
        self.db.add(record)
        return record.id

    def update_record(self, record_id: int, record_data: Dict[str, Any]) -> bool:
        """
        更新订单记录
        :param record_id: 记录ID
        :param record_data: 要更新的数据
        :return: 是否成功
        """
        record = self.db.get_by_id(OrderRecord, record_id)
        if not record:
            return False
            
        record_data = self._prepare_record_data(record_data)
        for key, value in record_data.items():
            setattr(record, key, value)
            
        self.db.update_obj(record)
        return True

    def update_buy_status(self, record_id: int, status: int, buy_at: str = None, desc: str = None) -> bool:
        """
        更新购买状态
        :param record_id: 记录ID
        :param status: 新状态
        :param buy_at: 购买时间
        :param desc: 失败原因描述
        :return: 是否成功
        """
        record = self.db.get_by_id(OrderRecord, record_id)
        if not record:
            return False
            
        record.buy_status = status
        if buy_at:
            record.buy_at = datetime.fromisoformat(buy_at.replace('Z', '+00:00'))
        if desc:
            record.offer_fail_desc = desc
            
        self.db.update_obj(record)
        return True

    def update_offer_status(self, record_id: int, status: int, desc: str = None, offer_at: str = None) -> bool:
        """
        更新报价状态
        :param record_id: 记录ID
        :param status: 新状态
        :param desc: 失败描述
        :param offer_at: 报价时间
        :return: 是否成功
        """
        record = self.db.get_by_id(OrderRecord, record_id)
        if not record:
            return False
            
        record.offer_status = status
        if desc:
            record.offer_fail_desc = desc
        if offer_at:
            record.offer_at = datetime.fromisoformat(offer_at.replace('Z', '+00:00'))
            
        # 更新报价次数
        if status in [2, 3, 4]:  # 报价中、成功、失败都算一次报价
            record.offer_times += 1
            
        self.db.update_obj(record)
        return True

    def delete_record(self, record_id: int) -> bool:
        """
        删除订单记录
        :param record_id: 记录ID
        :return: 是否成功
        """
        record = self.db.get_by_id(OrderRecord, record_id)
        if not record:
            return False
            
        self.db.delete_obj(record)
        return True

    def get_active_purchase_count(self, task_id: str) -> int:
        """
        获取指定任务的进行中和已完成的购买数量（非失败状态的记录数）
        :param task_id: 任务ID
        :return: 非失败状态的购买记录数量
        """
        session, query = self.db.query_with_session(OrderRecord)
        try:
            # 构建查询
            query = query.filter(
                OrderRecord.task_id == task_id,
                OrderRecord.buy_status != 0,  # 非初始状态
                OrderRecord.offer_status != 0  # 非初始状态
            )
            
            # 执行查询
            count = query.count()
            return count
        finally:
            session.close()

    def _prepare_record_data(self, record_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        处理记录数据，确保数据格式正确
        """
        data = record_data.copy()
        
        # 处理时间字段
        for field in ['create_at', 'update_at', 'buy_at', 'offer_at']:
            if field in data and data[field] and isinstance(data[field], str):
                data[field] = datetime.fromisoformat(data[field].replace('Z', '+00:00'))
                
        return data

    def _convert_model_to_dict(self, record: OrderRecord) -> Dict[str, Any]:
        """
        将OrderRecord模型转换为字典
        """
        if not record:
            return {}
            
        result = {
            'id': record.id,
            'account_id': record.account_id,
            'account_name': record.account_name,
            'script_id': record.script_id,
            'script_name': record.script_name,
            'task_id': record.task_id,
            'task_name': record.task_name,
            'order_no': record.order_no,
            'pay_order_no': record.pay_order_no,
            'wait_payment_data_no': record.wait_payment_data_no,
            'assetid': record.assetid,
            'name': record.name,
            'price': record.price,
            'game': record.game,
            'goods_id': record.goods_id,
            'market_hash_name': record.market_hash_name,
            'paintwear': record.paintwear,
            'expect_income': record.expect_income,
            'buy_status': record.buy_status,
            'pay_type': record.pay_type,
            'offer_status': record.offer_status,
            'offer_times': record.offer_times,
            'offer_fail_desc': record.offer_fail_desc
        }
        
        # 处理时间字段
        for field in ['create_at', 'update_at', 'buy_at', 'offer_at']:
            value = getattr(record, field)
            if value:
                result[field] = value.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
            else:
                result[field] = None
                
        return result
